package com.example.myblog.config;

import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 简单的启动时数据库迁移器：确保 treasure_items.icon 列长度为 500
 */
@Component
public class DatabaseMigrationRunner implements CommandLineRunner {

    private final JdbcTemplate jdbcTemplate;

    public DatabaseMigrationRunner(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void run(String... args) throws Exception {
        try {
            // 检查当前列长度
            Integer currentLen = jdbcTemplate.query(
                    "SELECT CHARACTER_MAXIMUM_LENGTH FROM information_schema.columns " +
                            "WHERE table_schema = DATABASE() AND table_name = 'treasure_items' AND column_name = 'icon'",
                    rs -> rs.next() ? rs.getInt(1) : null
            );

            if (currentLen == null) {
                // 表或列不存在，交由 JPA 创建；这里不做处理
                return;
            }

            if (currentLen < 500) {
                // 执行列长度扩展
                jdbcTemplate.execute("ALTER TABLE treasure_items MODIFY COLUMN icon VARCHAR(500)");
            }
        } catch (Exception ex) {
            // 迁移失败不影响应用启动，但记录日志以便排查
            System.err.println("[DB Migration] 扩展 treasure_items.icon 失败: " + ex.getMessage());
        }
    }
}